import { Component, OnInit, OnDestroy, Input, Output, EventEmitter, ElementRef, ViewChild } from '@angular/core';
import { EditorService } from './editor.service';

@Component({
    moduleId: module.id,
    selector: 'ng-editor',
    templateUrl: 'editor.component.html'
})
export class EditorComponent implements OnInit, OnDestroy {
    private ed: any;
    private htmlCodeValue: string;
    constructor(private editorSvr: EditorService) {
        this.editorSvr.Register(this);
    }

    getHtmlCode() {
        return document.getElementsByClassName("note-editable").item(0).innerHTML
    }
    setHtmlCode(value: string) {
        this.htmlCodeValue = value;
        let d = document.getElementsByClassName("note-editable").item(0);
        if (d) d.innerHTML = this.htmlCodeValue;
    }
    insertImage(imageUrl: string) {
        this.ed.summernote("insertImage", imageUrl, (e: any) => {
            console.log(e);
        });
    }

    @ViewChild("summernote")
    editor: ElementRef;

    ngOnInit() {
        let that = this;
        this.ed = $(this.editor.nativeElement)
        this.ed.summernote({
            lang: 'zh-CN',
            height: 300,
            callbacks: {
                onImageUpload: function (files: any) {
                    var f = files[0];
                    that.editorSvr.UploadImage && that.editorSvr.UploadImage(f);
                },
            }

        });
        if (this.htmlCodeValue)
            document.getElementsByClassName("note-editable").item(0).innerHTML = this.htmlCodeValue;
    }

    ngOnDestroy() {
        this.ed.summernote('destroy');
    }
}

declare const $: any;